package com.movisol.c2dm.controllers;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Context;

import com.movisol.c2dm.events.PushNotificationReceivedEvent;
import com.movisol.c2dm.events.RegistrationIdReceivedEvent;
import com.movisol.c2dm.ilisteners.IPushNotificationReceived;
import com.movisol.c2dm.ilisteners.IRegistrationIdReceived;


public class C2DMController {
	
	private static C2DMController INSTANCE = null;
	private List<IPushNotificationReceived> pushNotificationListener = new ArrayList<IPushNotificationReceived>();
	private List<IRegistrationIdReceived> registrationListener = new ArrayList<IRegistrationIdReceived>();
	private Context context;
	private String sui;
	
	private C2DMController()
	{}

	public static C2DMController getInstance()
	{
		if( INSTANCE == null)
			INSTANCE =  new C2DMController();
		
		return INSTANCE;
	}
	
	
	//Blocks the clone method
	@Override
	protected Object clone() throws CloneNotSupportedException{
		throw new CloneNotSupportedException("Clone is not allowed");
	}
	
	public void addPushNotificationsListener(IPushNotificationReceived listener)
	{
		if(!pushNotificationListener.contains(listener))
			pushNotificationListener.add(listener);
	}
	
	public void removePushNotificationsListener(IPushNotificationReceived listener)
	{
		pushNotificationListener.remove(listener);
	}
	
	public void firePushNotificationsListener()
	{
		PushNotificationReceivedEvent pnre = null;
		pnre = new PushNotificationReceivedEvent(this, sui);
		Iterator<IPushNotificationReceived> it = pushNotificationListener.listIterator();
		while (it.hasNext()){
			 it.next().pushNotificationReceived(pnre);
		}
	}
	
	public void addRegistrationListener(IRegistrationIdReceived listener)
	{
		if(!registrationListener.contains(listener))
			registrationListener.add(listener);
	}
	
	public void removeRegistrationListener(IRegistrationIdReceived listener)
	{
		registrationListener.remove(listener);
	}
	
	public void fireRegistrationListener(String registrationId)
	{
		RegistrationIdReceivedEvent rre = null;
		rre = new RegistrationIdReceivedEvent(this, registrationId);
		Iterator<IRegistrationIdReceived> it = registrationListener.listIterator();
		while (it.hasNext()){
			 it.next().registrationIdReceived(rre);
		}
	}

	public Context getContext() {
		return context;
	}

	public void setContext(Context context) {
		this.context = context;
	}

	public String getSui() {
		return sui;
	}

	public void setSui(String sui) {
		this.sui = sui;
	}
	
	
}
